package com.teamclub.erp.sservices

import io.ebean.{Ebean, ExpressionList}
import com.teamclub.domain.erp.product.ProductBrand
import com.teamclub.erp.sforms.ProductBrandForm
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

/**
  * Created by ilkkzm on 17-9-22.
  */
@Service
class ProductBrandService {
  def expr(where: ExpressionList[ProductBrand],form: ProductBrandForm) = {
    if(form.productId != null) {
      where.eq("productId", form.productId)
    }
    if(StringUtils.isNotBlank(form.organNo)) {
      where.eq("organNo", form.organNo)
    }
    where.eq("isDelete", false)
    where.orderBy("createdTime desc")
  }

  def list(form: ProductBrandForm): F.Either[Pager[ProductBrand], ErrorCode] = {
    val where = Ebean.find(classOf[ProductBrand]).where()
    expr(where, form)
    F.Either.Left(Pager.genePager(where.query(), form))
  }

  def add(form: ProductBrandForm): F.Either[ProductBrand, ErrorCode] = {
    var instance = new ProductBrand
    if(form.id != null) {
      instance = Ebean.find(classOf[ProductBrand], form.id)
    }
    if(instance == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    BeanUtils.copyProperties(form, instance)
    if(form.id != null) {
      instance.update()
    } else {
      instance.save()
    }
    F.Either.Left(instance)
  }

  def del(form: ProductBrandForm): F.Either[ProductBrand, ErrorCode] = {
    if(form.id == null) {
      return F.Either.Right(ErrorCode.BIZ_FAILURE)
    }
    val instance = Ebean.find(classOf[ProductBrand], form.id)
    if(instance == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    instance.setIsDelete(true)
    instance.update()
    F.Either.Left(instance)
  }
}
